/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include <stdlib.h>
#include <string.h>
#include <Lock.h>
#include <pthread.h>
#include <ParameterCheck.h>
#include <OSMemory.h>

typedef struct {
    pthread_mutex_t mutex;
} LockObjType;

#define LOCK_OBJ_TO_LOCK_HANDLER(x) (LockType)(x)
#define LOCK_HANDLER_TO_LOCK_OBJ(x) (LockObjType*)(x)

LockType newLock() {
    LockObjType* lockObj = (LockObjType*)OS_MALLOC(sizeof(LockObjType));
    if (!lockObj) {
        return NULL;
    }

    if (pthread_mutex_init(&lockObj->mutex, NULL) < 0) {
        OS_FREE(lockObj);
        return NULL;
    }

    return LOCK_OBJ_TO_LOCK_HANDLER(lockObj);
}
void deleteLock(LockType lock) {
    LockObjType* lockObj = LOCK_HANDLER_TO_LOCK_OBJ(lock);
    PARAMTER_CHECK_RETURN_VOID(lockObj != (void*)NULL);
    if (lockObj) {
        pthread_mutex_destroy(&lockObj->mutex);
        OS_FREE(lockObj);
    }
}
void lock(LockType lock) {
    LockObjType* lockObj = LOCK_HANDLER_TO_LOCK_OBJ(lock);
    PARAMTER_CHECK_RETURN_VOID(lockObj != NULL);
    pthread_mutex_lock(&lockObj->mutex);
}
void unlock(LockType lock) {
    LockObjType* lockObj = LOCK_HANDLER_TO_LOCK_OBJ(lock);
    PARAMTER_CHECK_RETURN_VOID(lockObj != NULL);
    pthread_mutex_unlock(&lockObj->mutex);
}

void* getLockObj(LockType lock) {
    LockObjType* lockObj = LOCK_HANDLER_TO_LOCK_OBJ(lock);
    PARAMTER_CHECK_RETURN_NULL(lockObj != NULL);
    return &lockObj->mutex;
}

